package MyAccumulator;

import common.In;
import common.StdDraw;
import common.StdOut;
import common.StdRandom;

/**
 * Copyright (C), 2020-2020, XXX有限公司
 * FileName: VisualAccumulator
 * Author:   cakin
 * Date:     2020/1/11
 * Description: 可视化累加器实现
 */
public class VisualAccumulator {
    private int n = 0;          // number of data values
    private double sum = 0.0;   // sample variance * (n-1)
    private double mu = 0.0;    // sample mean

    public VisualAccumulator(int trials,double max) {
        StdDraw.setXscale(0,trials);
        StdDraw.setYscale(0,max);
        StdDraw.setPenRadius(.005);
    }

    public void addDataValue(double x) {
        n++;
        double delta = x - mu;
        mu  += delta / n;
        sum += (double) (n - 1) / n * delta * delta;
        StdDraw.setPenColor(StdDraw.DARK_GRAY);
        StdDraw.point(n,x);
        StdDraw.setPenColor(StdDraw.RED);
        StdDraw.point(n,mu);
    }

    public double mean() {
        return mu;
    }

    public double var() {
        if (n <= 1) return Double.NaN;
        return sum / (n - 1);
    }

    public double stddev() {
        return Math.sqrt(this.var());
    }

    public int count() {
        return n;
    }

    public String toString() {
        return "n = " + n + ", mean = " + mean() + ", stddev = " + stddev();
    }

    public static void main( String[] args ) {
        int T = Integer.parseInt(args[0]);
        VisualAccumulator a = new VisualAccumulator(T,1.0);
        for(int t=0;t<T;t++){
            a.addDataValue(StdRandom.uniform());
        }
        StdOut.println(a);
    }
}
